<?php

namespace app\controllers\api;

use app\models\Member;
use app\models\News;
use app\models\User;
use Yii;
use yii\base\Exception;
use yii\base\UserException;
use yii\web\NotFoundHttpException;

class MemberController extends BaseController {
    public function actionCreate() {
        $user = $this->check();
        $this->checkModify();
        $post = Yii::$app->request->post();
        $model = Member::getByName($post['name']);
        if(!$model->isNewRecord && $model->status) {
            throw new UserException("{$model->status}已经在{$model->user->username}中任职");
        }
        $model->loadBeforeFilter($post, ['position', ]);
        $model->status = true;
        $model->user_id = $user->id;
        $model->salary = Member::$salaryArray[(int)$model->position];
        $model->save();
        $this->log('公司成员 - 创建', $model->id);
        return $this->renderSuccess([]);
    }

    public function actionList($position = null, $status = true) {
        $user = $this->check();
        $models = Member::find()
            ->andFilterWhere([
                'user_id' => $user->id,
                'position' => $position,
                'status' => $status,
            ])
            ->all();
        $this->log('公司成员 - 查询列表', '');
        return $this->renderSuccess([
            'list' => $models,
        ]);
    }
    public function actionDelete() {
        $user = $this->check();
        $this->checkModify();
        $post = Yii::$app->request->post();
        $model = Member::findOne(['name'=>$post['name']]);
        if(!$model || !$model->status) {
            throw new UserException("不存在该成员");
        }
        if($model->user_id != $user->id) {
            throw new UserException("不存在该成员");
        }
        $model->status = false;
        $model->save();
        $this->log('公司成员 - 辞退', $model->id);
        return $this->renderSuccess([]);
    }
}
